from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from .models import User, Address
from celery_tasks.email.tasks import send_verify_email


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class EmailSerializer(serializers.ModelSerializer):
    """保存邮箱的序列化器"""
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """更新，instance为要更新的对象实例"""
        instance.email = validated_data.get('email', instance.email)
        instance.save()

        # 发送验证链接
        verify_url = instance.generate_verify_email_url()
        send_verify_email.delay(instance.email, verify_url)
        return instance


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详细信息的序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class UserSerializer(serializers.ModelSerializer):
    """创建用户序列化器"""
    # 只写 只能进行反序列化  因为这三个自定义字段都不需要进行序列化操作
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="发送短信", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)
    token = serializers.CharField(label="状态保持", read_only=True)

    class Meta:
        model = User  # 指定模型类
        fields = ['id', 'username', 'password', 'password2', 'sms_code', 'allow', 'mobile', 'token']
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """校验手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def validate_allow(self, value):
        """检查用户是否勾选同意协议"""
        if value != 'true':
            raise serializers.ValidationError("请勾选同意协议")
        return value

    def validate(self, attrs):
        """校验两次密码是否一致&校验短信验证码"""
        if attrs["password"] != attrs["password2"]:
            raise serializers.ValidationError("两次密码不一致")

        redis_conn = get_redis_connection("verify_codes")
        mobile = attrs["mobile"]
        real_sms_code = redis_conn.get("sms_%s" % mobile).decode()
        sms_code = attrs["sms_code"]
        if not real_sms_code:
            raise serializers.ValidationError("验证码已经过期")
        if real_sms_code != sms_code:
            raise serializers.ValidationError("验证码错误")
        return attrs

    def create(self, validated_data):
        """重写ModelSerializer创建用户"""
        # 移除数据库模型类中不不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        # user = User.objects.create(**validated_data)
        user = User(**validated_data)
        # 调⽤用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token(手动生成token)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载生成载荷函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token函数
        payload = jwt_payload_handler(user)  # 生成载荷
        token = jwt_encode_handler(payload)  # 根据载荷生成token (因为header是固定的配置项目写法,所以该方法内部直接写死了header的获取值)
        # 直接将生成的token 赋值给user.token字段，多添加一个属性
        user.token = token

        return user
